<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\goods\Order;
use app\common\controller\Api;
use app\common\controller\Payment;
use think\Controller;
use think\Db;
use think\Request;


class Userdynamics extends Api
{
    private static $model;
//    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';


    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new \app\common\model\UserDynamics();
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function lists()
    {

        $pageSize = input('pagesize', 15);
        $page = input('page', 1);
        $start = ($page - 1) * $pageSize;

        $userId = $this->auth->id;
        $isMine = input('is_mine');
        if ($isMine == 1) {
            // 我自己发布的
            $where = [
                'status' => 1,
            ];

            $order = input('order', 'createtime');
            $sort = input('sort', 'desc');

            $list = self::$model->where($where)->order($order . ' ' . $sort)->limit($start, $pageSize)->select();
            $total = self::$model->where($where)->count();
        } else {
            // 别人发布的
            // 屏蔽动态
            $segregates_arr = \app\common\model\DynamicSegregates::where('user_id', $userId)->column('dynamic_id');
            $segregates_str = implode(',', $segregates_arr);
            // 黑名单
            $userIds_arr = \app\common\model\UserBlacks::where('user_id', $userId)->column('touser_id');
            $userIds_str = implode(',', $userIds_arr);

            // 1为关注，2为推荐，3为最新，4为附近
            $filterType = input('filter_type', 1);
            if ($filterType == 4) {
                $lon = input('lon');
                $lat = input('lat');
                if (!$lon || !$lat) {
                    $this->error('缺失定位参数！');
                }

                $lsql = "SELECT  g.*,(st_distance (point (longitude, latitude),point({$lon},{$lat}) ) / 0.0111) AS distance  FROM  fa_user_dynamics g where g.status = 1";
                $csql = "SELECT  count(*) as total,(st_distance (point (longitude, latitude),point({$lon},{$lat}) ) / 0.0111) AS distance  FROM  fa_user_dynamics g where g.status = 1";
                if ($segregates_str) {
                    $lsql .= " and g.id not in {$segregates_str}";
                    $csql .= " and g.id not in {$segregates_str}";
                }

                if ($userIds_str) {
                    $lsql .= " and g.user_id not in {$userIds_str}";
                    $csql .= " and g.user_id not in {$userIds_str}";
                }

                $lsql .= " order by distance asc limit {$start},{$pageSize}";

                $list = Db::query($lsql);
                $total = Db::query($csql);
                $total = $total[0]['total'];
            } else {
                $where = [
                    'status' => 1,
                    'id' => ['not in', $segregates_str],
                    'user_id' => ['not in', $userIds_str]
                ];

                $order = input('order', 'createtime');
                $sort = input('sort', 'desc');
                if ($filterType == 1) {
                    $userIds = \app\common\model\UserFans::where('fans_user_id', $userId)->column('user_id');
                    $where['user_id'] = ['in', $userIds];
                } elseif ($filterType == 2) {
                    $where['is_recom'] = 1;
                }

                $keyword = input('keyword');
                if ($keyword) {
                    $where['content'] = ['like', '%' . $keyword . '%'];
                }

                $list = self::$model->where($where)->order($order . ' ' . $sort)->limit($start, $pageSize)->select();
                $total = self::$model->where($where)->count();
            }

            if ($list) {
                foreach ($list as &$val) {
                    $val['user'] = \app\common\model\User::find($val['user_id']);
                    $fansId = \app\common\model\UserFans::where('user_id', $val['user_id'])->where('fans_user_id', $userId)->value('id');
                    if ($fansId) {
                        $isFans = true;
                    } else {
                        $isFans = false;
                    }

                    $val['is_fans'] = $isFans;

                    $praiseId = \app\common\model\DynamicPraises::where('user_id', $userId)->where('dynamic_id', $val['id'])->value('id');
                    $val['is_praise'] = $praiseId ? true : false;
                }
            }
        }

        $this->success('动态列表', ['current_page' => $page, 'data' => $list, 'per_page' => $pageSize, 'total' => $total]);
    }

    /**
     * 发布图文或者视频
     */
    public function create()
    {
        $type = input('type', 1);//1为图文，2为视频
        $title = input('title');
        $video_url = input('video_url');
        $pics = input('pics');
        $ground_types = input('ground_types');
        $content = input('content');
        $address = input('address');
        $longitude = input('longitude');
        $latitude = input('latitude');

        if (!in_array($type, [1, 2])) {
            $this->error('参数非法！');
        }

        if (!$ground_types) {
            $this->error('必须选择发帖类型！');
        }

        if (!$content) {
            $this->error('必须输入内容！');
        }

        if (!$address) {
            $this->error('必须选择具体地址！');
        }

        if (!$longitude || !$latitude) {
            $this->error('必须上传经纬度！');
        }

        $ddata = [
            'type' => $type,
            'user_id' => $this->auth->id,
            'ground_types' => $ground_types,
            'content' => $content,
            'address' => $address,
            'longitude' => $longitude,
            'latitude' => $latitude,
        ];

        switch ($type) {
            case 1:
                if (!$title) {
                    $this->error('请输入标题！');
                }
                if (!$pics) {
                    $this->error('请上传图片！');
                }
                $ddata['title'] = $title;
                $ddata['pics'] = $pics;
                break;
            case 2:
                if (!$video_url) {
                    $this->error('请上传视频！');
                }
                $ddata['video_url'] = $video_url;
                break;
        }

        $ret = \app\common\model\UserDynamics::create($ddata);
        if (!$ret->id) {
            $this->error('发布失败！');
        }

        \app\common\model\UserScoreLog::publishBonus($this->auth->id);

        $this->success('发布成功！');
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $id = input('id');
        $row_info = self::$model->find($id);
        if (!$row_info) {
            $this->error('该动态不存在！');
        }

        $title = input('title');
        $video_url = input('video_url');
        $pics = input('pics');
        $ground_types = input('ground_types');
        $content = input('content');
        $address = input('address');
        $longitude = input('longitude');
        $latitude = input('latitude');

        if (!$ground_types) {
            $this->error('必须选择发帖类型！');
        }

        if (!$content) {
            $this->error('必须输入内容！');
        }

        if (!$address) {
            $this->error('必须选择具体地址！');
        }

        if (!$longitude || !$latitude) {
            $this->error('必须上传经纬度！');
        }

        $ddata = [
            'ground_types' => $ground_types,
            'content' => $content,
            'address' => $address,
            'longitude' => $longitude,
            'latitude' => $latitude,
        ];
        $type = $row_info->type;//1为图文，2为视频
        switch ($type) {
            case 1:
                if (!$title) {
                    $this->error('请输入标题！');
                }
                if (!$pics) {
                    $this->error('请上传图片！');
                }
                $ddata['title'] = $title;
                $ddata['pics'] = $pics;
                break;
            case 2:
                if (!$video_url) {
                    $this->error('请上传视频！');
                }
                $ddata['video_url'] = $video_url;
                break;
        }

        $ret = \app\common\model\UserDynamics::where('id', $id)->update($ddata);
        if (!$ret->id) {
            $this->error('编辑失败！');
        }

        $this->success('编辑成功！');
    }

    /**
     * 详情
     */
    public function read()
    {
        $id = input('id');
        $row_info = self::$model->find($id);
        if (!$row_info) {
            $this->error('该动态不存在！');
        }

        $this->success('动态详情', $row_info);
    }

    /**
     * 删除
     */
    public function del()
    {
        $id = input('id');
        $row_info = self::$model->find($id);
        if (!$row_info) {
            $this->error('该动态不存在！');
        }

        $ret = self::$model->where('id', $id)->delete();
        if (!$ret) {
            $this->error('删除失败！');
        }
        $this->success('删除成功！');
    }


}
